package org.stars.daostars.sqlmapper.loader.xml;

import org.stars.daostars.conversion.DefaultTypeHandler;
import org.stars.daostars.conversion.TypeAlias;
import org.stars.daostars.conversion.TypeHandler;
import org.stars.daostars.core.SqlQuery;
import org.stars.daostars.sqlmapper.SqlMapper;
import org.stars.util.StringUtility;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.xml.sax.Attributes;

/**
 * Gestore del tag variable.
 * 
 * @author Francesco Benincasa (908099)
 *
 */
public abstract class TypeHandlerTagHandler {
	private static final String NAME = "name";
	private static final String CLASS = "class";
	

	protected static Log getLog()
	{
		return LogFactory.getLog(TypeHandlerTagHandler.class);
	}
	
	public static SqlMapper startElement(SqlMapper definition, SqlQuery query, Attributes attributes)	
	{
		String sName = StringUtility.nvl(attributes.getValue(NAME)).toUpperCase().trim();
		String sClazz = StringUtility.nvl(attributes.getValue(CLASS)).trim();

		TypeAlias typeAlias = new TypeAlias();
		TypeHandler handler = null;
		
		try {
			handler = (TypeHandler) Class.forName(sClazz).newInstance();			
		} catch (Exception e) {
			String msg = "Dao " + definition.getName() + ", query " + query.getName()+ ": Can not use typeHandler " + sClazz + " for alias " + sName + ".";
			Log logger=getLog();
			logger.error(msg);
			definition.addParserError(msg, e.getClass());
			handler = new DefaultTypeHandler();			
		}
		typeAlias.setHandler(handler);
		definition.setTypeAlias(sName, typeAlias);
		
		return definition;
	}
}
